<!--
*Author：COCO
 *代码由框架生成,任何更改都可能导致被代码生成器覆盖
 *业务请在@/extension/new_qualitytest/inboundtest/InspectionDetail.js此处编写
 -->
<template>
    <div class="inspection-list-container">
        <!-- 顶部搜索和按钮区域 -->
        <div class="search-form">
            <el-form :inline="true" :model="searchModel" class="demo-form-inline">
                <el-form-item label="检验单号">
                    <el-input v-model="searchModel.InspectionOrderCode" placeholder="请输入检验单号"></el-input>
                </el-form-item>
                <el-form-item label="检验主题">
                    <el-input v-model="searchModel.InspectionSubject" placeholder="请输入检验主题"></el-input>
                </el-form-item>
                <el-form-item label="检验日期">
                    <el-date-picker
                        v-model="searchModel.InspectionDate"
                        type="date"
                        placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="searchData">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        
        <!-- 按钮工具栏 -->
        <div class="tool-bar">
            <el-button type="primary" @click="addNew">新增</el-button>
            <el-button @click="exportData">导出</el-button>
            <!-- 搜索框 -->
            <div class="search-box">
                <el-input 
                    v-model="quickSearchText" 
                    placeholder="请输入搜索内容" 
                    @keyup.enter="quickSearch">
                    <template #append>
                        <el-button icon="el-icon-search" @click="quickSearch"></el-button>
                    </template>
                </el-input>
            </div>
            <!-- 视图切换按钮 -->
            <el-button icon="el-icon-menu" class="view-toggle"></el-button>
        </div>
        
        <!-- 表格区域 -->
        <el-table
            :data="tableData"
            style="width: 100%"
            border
            stripe
            @selection-change="handleSelectionChange"
            v-loading="loading">
            <el-table-column
                type="selection"
                width="55">
            </el-table-column>
            <el-table-column
                type="index"
                label="序号"
                width="60">
            </el-table-column>
            <el-table-column
                prop="InspectionOrderCode"
                label="检验单号"
                width="150">
            </el-table-column>
            <el-table-column
                prop="InspectionSubject"
                label="检验单主题"
                width="180">
            </el-table-column>
            <el-table-column
                prop="InspectionDate"
                label="检验日期"
                width="120">
            </el-table-column>
            <el-table-column
                prop="MaterialSummary"
                label="物品概要"
                width="180">
                <template #default="scope">
                    <el-popover
                        placement="right"
                        width="300"
                        trigger="hover"
                        v-if="scope.row.MaterialSummary">
                        <template #default>
                            <div class="material-summary-detail">
                                <!-- 显示物品明细 -->
                                <div v-for="(item, index) in parseMaterialSummary(scope.row.MaterialSummary)" :key="index">
                                    <p>产品{{ item.code }}: {{ item.count }}</p>
                                </div>
                            </div>
                        </template>
                        <template #reference>
                            <span>{{ scope.row.MaterialSummary || '新产品等10项' }}</span>
                        </template>
                    </el-popover>
                    <span v-else>新产品等10项</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="Inspector"
                label="检验人"
                width="100">
            </el-table-column>
            <el-table-column
                prop="Department"
                label="所在部门"
                width="120">
            </el-table-column>
            <el-table-column
                prop="order_no"
                label="采购单号"
                width="150">
            </el-table-column>
            <el-table-column
                prop="inspectorRemark"
                label="备注"
                width="150">
            </el-table-column>
            <el-table-column
                fixed="right"
                label="操作"
                width="100">
                <template #default="scope">
                    <el-button type="text" size="small" class="view-btn" @click="viewDetail(scope.row)">查看</el-button>
                </template>
            </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
            <div class="pagination-info">
                共{{ total }}项数据
            </div>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageIndex"
                :page-sizes="[5, 10, 20, 50]"
                :page-size="pageSize"
                layout="sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
            <div class="pagination-goto">
                跳至
                <el-input v-model="gotoPage" size="small" @keyup.enter="handleJump"></el-input>
                页
            </div>
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted, defineComponent } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import http from '@/api/http';
import { useRouter } from 'vue-router';

    export default defineComponent({
    name: 'Show_InboundTest',
        setup() {
        const router = useRouter();
        // 表格数据
        const tableData = ref([]);
        const loading = ref(false);
        const total = ref(0);
        const pageIndex = ref(1);
        const pageSize = ref(5);
        const selectedRows = ref([]);
        const quickSearchText = ref('');
        const gotoPage = ref('');
        
        // 搜索模型
        const searchModel = reactive({
            InspectionOrderCode: '',
            InspectionSubject: '',
            InspectionDate: ''
        });
        
        // 获取列表数据的方法
        const loadData = () => {
            loading.value = true;
            
            // 构建查询条件
            const whereList = [];
            
            if (searchModel.InspectionOrderCode) {
                whereList.push({
                    name: 'InspectionOrderCode',
                    value: searchModel.InspectionOrderCode
                });
            }
            
            if (searchModel.InspectionSubject) {
                whereList.push({
                    name: 'InspectionSubject',
                    value: searchModel.InspectionSubject
                });
            }
            
            if (searchModel.InspectionDate) {
                const date = new Date(searchModel.InspectionDate);
                const dateString = date.toISOString().split('T')[0];
                whereList.push({
                    name: 'InspectionDate',
                    value: dateString
                });
            }
            
            // API调用参数，严格按照后端API要求的格式
            const params = {
                page: pageIndex.value,
                rows: pageSize.value,
                sort: 'CreateDate',
                order: 'desc',
                wheres: JSON.stringify(whereList)
            };
            
            console.log('发送到后端的参数:', params);
            
            http.post('/api/Quality_InboundTest/GetInboundWithOrder', params, true)
                .then(res => {
                    loading.value = false;
                    console.log('API返回数据:', res);
                    if (res.status === 0 || res.status === true) { // 处理不同的成功状态值
                        // 处理API返回的数据
                        handleApiResponse(res);
                    } else {
                        ElMessage.error(res.msg || res.message || '获取数据失败');
                        tableData.value = [];
                        total.value = 0;
                    }
                })
                .catch(err => {
                    loading.value = false;
                    console.error('获取数据异常:', err);
                    ElMessage.error('获取数据异常: ' + (err.message || '未知错误'));
                    tableData.value = [];
                    total.value = 0;
                });
        };
        
        // 处理API返回的数据
        const handleApiResponse = (response) => {
            let rows = [];
            let totalCount = 0;
            
            console.log('原始API响应数据:', response);
            
            // 根据后端API返回的实际格式提取数据
            if (response && response.rows && Array.isArray(response.rows)) {
                // 标准格式：{ status: 0, msg: "OK", total: 100, rows: [...] }
                rows = response.rows;
                totalCount = response.total || rows.length;
            } else if (response && response.data) {
                // 可能的包装格式：{ status: true, data: { rows: [...], total: 100 } }
                if (response.data.rows && Array.isArray(response.data.rows)) {
                    rows = response.data.rows;
                    totalCount = response.data.total || rows.length;
                } else if (Array.isArray(response.data)) {
                    // 可能的格式：{ status: true, data: [...] }
                    rows = response.data;
                    totalCount = response.data.length;
                }
            } else if (Array.isArray(response)) {
                // 纯数组格式
                rows = response;
                totalCount = response.length;
            }
            
            // 打印第一行数据的所有字段，方便排查问题
            if (rows.length > 0) {
                console.log('第一行数据的所有字段:', Object.keys(rows[0]));
                console.log('第一行数据的值:', rows[0]);
            }
            
            console.log('处理后的行数据:', rows);
            console.log('总数据量:', totalCount);
            
            // 处理字段名称不一致的问题
            if (rows.length > 0) {
                tableData.value = rows.map(row => {
                    // 为每个row对象添加大小写兼容的字段
                    const normalizedRow = { ...row };
                    
                    // 特殊处理采购单号字段
                    if (normalizedRow.order_no && !normalizedRow.purchaseOrderCode) {
                        normalizedRow.purchaseOrderCode = normalizedRow.order_no;
                    }
                    
                    // 特殊处理备注字段
                    if (normalizedRow.inspectorRemark && !normalizedRow.remark) {
                        normalizedRow.remark = normalizedRow.inspectorRemark;
                    }
                    
                    // 遍历row对象的所有属性
                    Object.keys(row).forEach(key => {
                        // 如果是小驼峰命名，添加对应的大驼峰属性
                        if (key.length > 0 && key[0] === key[0].toLowerCase()) {
                            const pascalKey = key[0].toUpperCase() + key.slice(1);
                            if (normalizedRow[pascalKey] === undefined) {
                                normalizedRow[pascalKey] = row[key];
                            }
                        }
                        
                        // 如果是大驼峰命名，添加对应的小驼峰属性
                        if (key.length > 0 && key[0] === key[0].toUpperCase()) {
                            const camelKey = key[0].toLowerCase() + key.slice(1);
                            if (normalizedRow[camelKey] === undefined) {
                                normalizedRow[camelKey] = row[key];
                            }
                        }
                    });
                    
                    return normalizedRow;
                });
            } else {
                tableData.value = [];
            }
            
            total.value = totalCount;
        };
        
        // 解析物品概要
        const parseMaterialSummary = (summary) => {
            if (!summary) return [];
            
            try {
                // 尝试解析物品概要格式
                // 示例格式: 产品0215: 3\n产品032: 1\n产品: 2\n产品三: 2\n新产品: 2
                const lines = summary.split('\n');
                return lines.map(line => {
                    const parts = line.split(':');
                    return {
                        code: parts[0].trim(),
                        count: parts[1] ? parseInt(parts[1].trim()) : 0
                    };
                });
            } catch (e) {
                console.error('解析物品概要失败:', e);
                return [];
            }
        };
        
        // 搜索数据
        const searchData = () => {
            pageIndex.value = 1;
            loadData();
        };
        
        // 重置搜索
        const resetSearch = () => {
            searchModel.InspectionOrderCode = '';
            searchModel.InspectionSubject = '';
            searchModel.InspectionDate = '';
            searchData();
        };
        
        // 快速搜索
        const quickSearch = () => {
            if (!quickSearchText.value) {
                return;
            }
            
            // 构建快速搜索条件，搜索检验单号、检验主题、检验人
            const whereList = [
                {
                    name: 'InspectionOrderCode',
                    value: quickSearchText.value
                },
                {
                    name: 'InspectionSubject',
                    value: quickSearchText.value
                },
                {
                    name: 'Inspector',
                    value: quickSearchText.value
                }
            ];
            
            // 使用OR逻辑进行搜索
            const params = {
                page: pageIndex.value,
                rows: pageSize.value,
                sort: 'CreateDate',
                order: 'desc',
                wheres: JSON.stringify(whereList),
                searchType: 'or' // 使用OR逻辑
            };
            
            console.log('快速搜索参数:', params);
            
            loading.value = true;
            http.post('/api/Quality_InboundTest/GetInboundWithOrder', params, true)
                .then(res => {
                    loading.value = false;
                    if (res.status === 0 || res.status === true) {
                        handleApiResponse(res);
                    } else {
                        ElMessage.error(res.msg || res.message || '搜索失败');
                        tableData.value = [];
                        total.value = 0;
                    }
                })
                .catch(err => {
                    loading.value = false;
                    ElMessage.error('搜索异常: ' + (err.message || '未知错误'));
                    tableData.value = [];
                    total.value = 0;
                });
        };
        
        // 新增按钮
        const addNew = () => {
            router.push('/new_qualitytest/inboundtest/Quality_InboundTest');
        };
        
        // 导出数据
        const exportData = () => {
            ElMessage.info('导出功能正在开发中...');
        };
        
        // 查看明细
        const viewDetail = (row) => {
            console.log('点击查看详情，行数据:', row);
            console.log('检验单ID:', row.inspectionOrderID || row.InspectionOrderID);
            
            // 导航到详情页面
            const routeTarget = {
                path: `/new_qualitytest/inboundtest/Detail_InboundTest`,
                query: {
                    id: row.inspectionOrderID || row.InspectionOrderID
                }
            };
            
            console.log('准备跳转到:', routeTarget);
            
            try {
                router.push(routeTarget);
                console.log('跳转已执行');
            } catch (error) {
                console.error('路由跳转失败:', error);
                // 尝试使用别名路径
                router.push({
                    path: '/Detail_InboundTest',
                    query: {
                        id: row.inspectionOrderID || row.InspectionOrderID
                    }
                });
            }
        };
        
        // 表格选择项变化
        const handleSelectionChange = (val) => {
            selectedRows.value = val;
        };
        
        // 分页大小变化
        const handleSizeChange = (size) => {
            pageSize.value = size;
            loadData();
        };
        
        // 页码变化
        const handleCurrentChange = (page) => {
            pageIndex.value = page;
            loadData();
        };
        
        // 跳转页码
        const handleJump = () => {
            if (!gotoPage.value) {
                return;
            }
            
            const page = parseInt(gotoPage.value);
            if (isNaN(page) || page < 1) {
                ElMessage.warning('请输入有效的页码');
                return;
            }
            
            const maxPage = Math.ceil(total.value / pageSize.value);
            if (page > maxPage) {
                pageIndex.value = maxPage;
            } else {
                pageIndex.value = page;
            }
            
            gotoPage.value = '';
            loadData();
        };
        
        // 组件挂载时加载数据
        onMounted(() => {
            loadData();
        });
        
            return {
            tableData,
            loading,
            total,
            pageIndex,
            pageSize,
            selectedRows,
            quickSearchText,
            gotoPage,
            searchModel,
            loadData,
            searchData,
            resetSearch,
            quickSearch,
            addNew,
            exportData,
            viewDetail,
            handleSelectionChange,
            handleSizeChange,
            handleCurrentChange,
            handleJump,
            parseMaterialSummary
        };
    }
    });
</script>

<style scoped>
.inspection-list-container {
    padding: 20px;
    background-color: #f5f7fa;
}

.search-form {
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 15px;
}

.tool-bar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
}

.search-box {
    width: 250px;
    margin-left: auto;
    margin-right: 10px;
}

.view-toggle {
    margin-left: 10px;
}

.pagination-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20px;
    background-color: #fff;
    padding: 10px 15px;
    border-radius: 4px;
}

.pagination-info {
    color: #606266;
}

.pagination-goto {
    display: flex;
    align-items: center;
    color: #606266;
}

.pagination-goto .el-input {
    width: 50px;
    margin: 0 5px;
}

.material-summary-detail {
    padding: 5px;
}

.material-summary-detail p {
    margin: 5px 0;
}

.view-btn {
    color: #409EFF;
}
</style>
